package com.frontop.system.modules.sale.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.net.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.frontop.common.annotation.AnonymousAccess;
import com.frontop.common.domain.UserJurisdiction;
import com.frontop.common.util.JwtUtil;
import com.frontop.common.util.RequestUtil;
import com.frontop.common.util.ResultJsonUtil;
import com.frontop.system.modules.sale.model.SaleInfo;
import com.frontop.system.modules.sale.model.SaleQrInfo;
import com.frontop.system.modules.sale.model.SaleQrStatis;
import com.frontop.system.modules.sale.service.SaleInfoService;
import com.frontop.system.modules.sale.service.SaleQrInfoService;
import com.frontop.system.modules.sale.service.SaleQrStatisService;
import com.frontop.system.modules.sale.vo.SaleQrInfoVO;
import com.frontop.system.modules.sale.vo.SaleQrStatisVO;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 二维码扫码统计 前端控制器
 * </p>
 *
 * @author YangJia
 * @since 2022-04-24
 */
@RestController
@RequestMapping("/sale-qr-statis")
public class SaleQrStatisController {
    @Autowired
    private SaleQrStatisService saleQrStatisService;
    @Autowired
    private SaleInfoService saleInfoService;

    @Autowired
    private SaleQrInfoService saleQrInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//可以写很多类型的值


    @ApiOperation(value = "扫码用户列表")
    @PostMapping("/qrStatisticsPage")
    public ResultJsonUtil<Object> qrStatisticsPage(@RequestBody(required = false) SaleQrStatisVO vo,
                                                  Authentication authentication) {
        //获取当前登录用户基本权限信息
        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        vo.setLowerOrganizationIds(userJurisdiction.getLowerOrganizationIds());
        Page<SaleQrStatis> page = new Page<>(vo.getPageNo(), vo.getPageSize());
        page = saleQrStatisService.qrStatisticsPage(page,vo);
        return new ResultJsonUtil().success(page);
    }


    @ApiOperation(value = "通过链接收集分享数量API")
    @GetMapping("/scanningQRCode/{saleId}/{qrId}")
    @AnonymousAccess
    public ResultJsonUtil<Object> scanningQRCode(@PathVariable("qrId") String qrId,
                                                 @PathVariable("saleId")String saleId,
                                                 HttpServletRequest request) {

        /**
         * 验证参数--开始
         */
        if(StringUtils.isEmpty(saleId) || StringUtils.isEmpty(qrId)){
            return new ResultJsonUtil().error("请携带要求参数");
        }
        QueryWrapper<SaleInfo> saleQu = new QueryWrapper<SaleInfo>();
        saleQu.eq("uuid",saleId);
        SaleInfo saleInfo = saleInfoService.getOne(saleQu);
        if(saleInfo == null){
            return new ResultJsonUtil().error("saleId无效");
        }
        QueryWrapper<SaleQrInfo> qrInfo = new QueryWrapper<SaleQrInfo>();
        qrInfo.eq("uuid",qrId);
        SaleQrInfo saleQrInfo = saleQrInfoService.getOne(qrInfo);
        if(saleQrInfo == null){
            return new ResultJsonUtil().error("qrId无效");
        }
        //返回信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone",saleInfo.getSalePhone());
        jsonObject.put("name",saleInfo.getSaleName());
        jsonObject.put("address",saleQrInfo.getAddress()+"?qrId="+saleQrInfo.getUuid()+"&saleId="+saleInfo.getUuid());
        jsonObject.put("headImage",saleInfo.getHeadPath());
        /**
         * 检查缓存--开始限制恶意刷分享量
         */

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        String clientType = userAgent.getOperatingSystem().getDeviceType().toString();//客户端类型  手机、电脑、平板
        String os = userAgent.getOperatingSystem().getName(); //操作系统类型
        String browser = userAgent.getBrowser().toString();//浏览器类型
        //获取请求者IP
        String ip = RequestUtil.getIpAddr(request);
        //客户端类型-手机-电脑-平板-qrId-saleId

        String redisCach = clientType+"-"+os+"-"+browser+"-"+ip+"-"+qrId+"-"+saleId;
        boolean haskey = stringRedisTemplate.hasKey(redisCach);

        if(haskey){
            return new ResultJsonUtil().success(jsonObject);
        }

        //设置缓存
        stringRedisTemplate.opsForValue().set(redisCach,"1",1, TimeUnit.HOURS);
        SaleQrStatis saleQrStatis = new SaleQrStatis();
        saleQrStatis.setClient(clientType);
        saleQrStatis.setOs(os);
        saleQrStatis.setBrowser(browser);
        saleQrStatis.setSaleUuid(saleId);
        saleQrStatis.setQrUuid(qrId);
        saleQrStatis.setCreateTime(new Date());
        saleQrStatis.setIp(ip);
        //根据腾讯位置服务过去地理信息
        String cityInfo = TXServer.getCityInfo(ip);
        if(StringUtils.isNotBlank(cityInfo)){
            saleQrStatis.setPro(cityInfo.split("-")[0].replace("省",""));
            saleQrStatis.setCity(cityInfo.split("-")[1]);
        }
        saleQrStatisService.save(saleQrStatis);

        return new ResultJsonUtil().success(jsonObject);
    }



    @ApiOperation(value = "获取销售传播总分享数、当日分享数、平均日分享数")
    @PostMapping("/getTotalStatics")
    public ResultJsonUtil<Object> getTotalStatics(@RequestBody(required = false) Map<String,Object> map,
                                         Authentication authentication) {
        if(map == null){
            map = new HashMap<>();
        }
        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        map.put("organization",userJurisdiction.getOrganizationId());
        Map<String,Object> data = saleQrStatisService.getTotalStatics(map);
        return new ResultJsonUtil().success(data);
    }

    @ApiOperation(value = "获取近30日分享统计")
    @PostMapping("/getQr30near")
    public ResultJsonUtil<Object> getQr30near(@RequestBody(required = false) Map<String,Object> map,
                                                  Authentication authentication) {
        if(map == null){
            map = new HashMap<>();
        }
        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        map.put("organization",userJurisdiction.getOrganizationId());
        List<Map<String,Object>> data = saleQrStatisService.getQr30near(map);
        return new ResultJsonUtil().success(data);
    }

    @ApiOperation(value = "获取排行榜（包含子企业）")
    @GetMapping("/getSort")
    public ResultJsonUtil<Object> getSort(Authentication authentication) {
        //获取当前登录用户基本权限信息
        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        Map<String,Object> map = new HashMap<>();
        map.put("lowerOrganizationIds",userJurisdiction.getLowerOrganizationIds());
        List<Map<String,Object>> data = saleQrStatisService.getSort(map);
        return new ResultJsonUtil().success(data);
    }



    @ApiOperation(value = "获取用户意向分布")
    @GetMapping("/getMpsStatis")
    public ResultJsonUtil<Object> getMpsStatis(Authentication authentication) {
        //获取当前登录用户基本权限信息
        UserJurisdiction userJurisdiction = JwtUtil.getUserJurisdiction(authentication);
        Map<String,Object> map = new HashMap<>();
        map.put("lowerOrganizationIds",userJurisdiction.getLowerOrganizationIds());
        List<Map<String,Object>> data = saleQrStatisService.getMpsStatis(map);
        return new ResultJsonUtil().success(data);
    }
}
